<template>
  <div class="limit-management">
    <div class="page-header">
      <h2>限时营销管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="活动名称">
          <el-input v-model="searchForm.limitName" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.limitState" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchLimits">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增限时营销
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="limitList" v-loading="loading" stripe>
        <el-table-column prop="limitId" label="活动ID" width="80" />
        <el-table-column prop="limitName" label="活动名称" width="200" />
        <el-table-column prop="beforePrice" label="原价" width="120">
          <template #default="{ row }">
            <span class="price-original">¥{{ row.beforePrice?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="afterPrice" label="折扣价" width="120">
          <template #default="{ row }">
            <span class="price-discount">¥{{ row.afterPrice?.toFixed(2) || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inventoryNum" label="库存" width="100">
          <template #default="{ row }">
            <el-tag :type="row.inventoryNum > 10 ? 'success' : row.inventoryNum > 0 ? 'warning' : 'danger'">
              {{ row.inventoryNum || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="limitState" label="活动状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getLimitStateType(row.limitState)">
              {{ getLimitStateText(row.limitState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editLimit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteLimit(row.limitId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑限时营销' : '新增限时营销'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="limitForm" :rules="limitRules" ref="limitFormRef" label-width="100px">
        <el-form-item label="活动名称" prop="limitName">
          <el-input v-model="limitForm.limitName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="原价" prop="beforePrice">
          <el-input-number v-model="limitForm.beforePrice" :min="0" :precision="2" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="折扣价" prop="afterPrice">
          <el-input-number v-model="limitForm.afterPrice" :min="0" :precision="2" placeholder="请输入折扣价" />
        </el-form-item>
        <el-form-item label="库存" prop="inventoryNum">
          <el-input-number v-model="limitForm.inventoryNum" :min="0" placeholder="请输入库存数量" />
        </el-form-item>
        <el-form-item label="活动状态" prop="limitState">
          <el-select v-model="limitForm.limitState" placeholder="请选择状态">
            <el-option label="进行中" :value="1" />
            <el-option label="已终止" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="limitForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="limitForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { limitApi } from '@/api/limit'

// 响应式数据
const loading = ref(false)
const limitList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const limitFormRef = ref()

// 搜索表单
const searchForm = reactive({
  limitName: '',
  limitState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 限时营销表单
const limitForm = reactive({
  limitId: null,
  limitName: '',
  beforePrice: 0,
  afterPrice: 0,
  inventoryNum: 0,
  limitState: 1,
  startTime: '',
  endTime: ''
})

// 表单验证规则
const limitRules = {
  limitName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  beforePrice: [
    { required: true, message: '请输入原价', trigger: 'blur' }
  ],
  afterPrice: [
    { required: true, message: '请输入折扣价', trigger: 'blur' }
  ],
  inventoryNum: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  limitState: [
    { required: true, message: '请选择活动状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 获取活动状态文本
const getLimitStateText = (state) => {
  const stateMap = {
    1: '进行中',
    2: '已终止'
  }
  return stateMap[state] || '未知'
}

// 获取活动状态标签类型
const getLimitStateType = (state) => {
  const stateMap = {
    1: 'success',
    2: 'danger'
  }
  return stateMap[state] || 'info'
}

// 搜索限时营销
const searchLimits = async () => {
  loading.value = true
  try {
    const response = await limitApi.getLimitList(searchForm)
    if (response.code === 200) {
      limitList.value = response.data || []
      pagination.total = limitList.value.length
    }
  } catch (error) {
    console.error('搜索限时营销失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    limitName: '',
    limitState: null
  })
  searchLimits()
}

// 编辑限时营销
const editLimit = (row) => {
  isEdit.value = true
  Object.assign(limitForm, row)
  showAddDialog.value = true
}

// 删除限时营销
const deleteLimit = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个限时营销活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await limitApi.deleteLimit(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchLimits()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除限时营销失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await limitFormRef.value.validate()

    const response = isEdit.value
      ? await limitApi.updateLimit(limitForm)
      : await limitApi.addLimit(limitForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchLimits()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(limitForm, {
    limitId: null,
    limitName: '',
    beforePrice: 0,
    afterPrice: 0,
    inventoryNum: 0,
    limitState: 1,
    startTime: '',
    endTime: ''
  })
  isEdit.value = false
  limitFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchLimits()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchLimits()
}

// 初始化
onMounted(() => {
  searchLimits()
})
</script>

<style scoped>
.limit-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.price-original {
  text-decoration: line-through;
  color: #999;
}

.price-discount {
  color: #f56c6c;
  font-weight: bold;
}
</style>